const express = require("express");
const app = express();
let chatObj = {}

const { Server } = require("socket.io");

const io = new Server(3000, {
    cors: {
        origin: ["http://localhost:8080"]
    }
})

let userList = []

io.on("connection", (socket) => {
    let userName = socket.handshake.query.username;
    // if(userName){
    //     return 0
    // }
    // ...
    // console.log("connected online",socket.handshake.query,socket.id)
    let userInfo = userList.find(user => user.username == userName)
    if (userInfo) {
        userInfo.id = socket.id;
    } else {
        userList.push({ id: socket.id, username: userName })
    }
    console.log(userList)
    io.emit('online', {
        userList
    })
    // io.emit 广播事件

    // 监听发送过来的信息
    socket.on('send', ({ fromUsername, targetId, msg }) => {
        console.log("onlineuser", fromUsername, targetId, msg)
        //    console.log(io.sockets.sockets)
        if (targetId) {
            const targetSocket = io.sockets.sockets.get(targetId)
            const toUser = userList.find(user => user.id == targetId)
            targetSocket.emit('receive', {
                fromUsername,
                toUsername: toUser.username,
                msg,
                dateTime: new Date().getTime()
            })
        }



    })
    // if(chatObj.targetId==)


});


app.listen(3001, () => {
    console.log("listening on http://localhost:3001")
})


